/*
 *  Class name: SoccerMatchHandler.java
 *  Version: 1.0
 *  Date: 4.4.2014
 */
package cz.muni.fi.pa165.soccergamesarchive.utils;

import cz.muni.fi.pa165.soccergamesarchive.businesslayer.dtos.GoalDTO;
import cz.muni.fi.pa165.soccergamesarchive.businesslayer.dtos.SoccerMatchDTO;
import cz.muni.fi.pa165.soccergamesarchive.businesslayer.dtos.SoccerMatchDetailDTO;
import cz.muni.fi.pa165.soccergamesarchive.businesslayer.dtos.TeamDTO;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static java.util.Collections.emptyList;

/**
 *
 * @author Michal Ďuriš
 */
public class SoccerMatchHandler {

    private SoccerMatchHandler() {
    }

    public static SoccerMatchDetailDTO createMatchDetail(SoccerMatchDTO match) {

        SoccerMatchDetailDTO matchDetail = new SoccerMatchDetailDTO();
        List<GoalDTO> homeTeamGoals = new ArrayList<>();
        List<GoalDTO> awayTeamGoals = new ArrayList<>();

        matchDetail.setId(match.getId());

        matchDetail.setStadiumName(match.getStadiumName());
        matchDetail.setMatchDate(match.getMatchDate());

        matchDetail.setHomeTeam(match.getHomeTeam());
        matchDetail.setAwayTeam(match.getAwayTeam());

        for (GoalDTO goal : match.getGoals()) {

            if (Objects.equals(goal.getPlayer().getTeam(), matchDetail
                    .getHomeTeam())) {
                homeTeamGoals.add(goal);
            } else {
                awayTeamGoals.add(goal);
            }
        }

        matchDetail.setHomeTeamGoals(homeTeamGoals);
        matchDetail.setAwayTeamGoals(awayTeamGoals);

        return matchDetail;
    }

    public static List<GoalDTO> getTeamGoals(TeamDTO team,
                                             List<GoalDTO> soccerMatchGoals) {

        if (soccerMatchGoals != null && !soccerMatchGoals.isEmpty()
                && team != null) {

            List<GoalDTO> teamGoals = new ArrayList<>(soccerMatchGoals.size());

            for (GoalDTO goal : soccerMatchGoals) {

                if (Objects.equals(goal.getPlayer().getTeam(), team)) {
                    teamGoals.add(goal);
                }
            }

            return teamGoals;
        }

        return emptyList();
    }

    public static String getSoccerMatchScore(SoccerMatchDTO soccerMatch) {

        if (soccerMatch == null) {
            return null;
        }

        int homeTeamGoals = 0, awayTeamGoals = 0;

        for (GoalDTO goal : soccerMatch.getGoals()) {

            if (Objects.equals(goal.getPlayer().getTeam().getId(),
                    soccerMatch.getHomeTeam().getId())) {

                homeTeamGoals++;
            } else {

                awayTeamGoals++;
            }
        }

        return homeTeamGoals + " : " + awayTeamGoals;
    }

}
